<template>
    <div id="login-box">
        <div class="login-form">
            <h3 style="text-align:center;">CRM管理系统</h3>
            <div class="login-input">
                <el-input v-model="username" placeholder="请输入登录用户名" autofocus maxlength="10" prefix-icon="User" />
            </div>
            <div class="login-input">
                <el-input v-model="password" type="password" placeholder="请输入登录密码" maxlength="20" prefix-icon="Lock" />
            </div>

            <div class="login-btn">
                <el-button class="btn" type="primary" round @click="login" 
                    :disabled="isLoginBtnDisabled">{{ loginBtnValue
                    }}</el-button>
            </div>
        </div>
    </div>
</template>
<script>
import { ref, toRefs, reactive, watch, onMounted, onUnmounted } from "vue";
import { doLogin } from '@/request/api'
export default {
    setup() {
        const isLoginBtnDisabled = ref(true)
        const loginBtnValue = ref('登 录')
        const user = reactive({
            username: '',
            password: ''
        })
        // 监听用户名及密码，是否禁用登录按钮
        watch(user, value => {
            isLoginBtnDisabled.value = user.username && user.password ? false : true
        }, { deep: true })

        onMounted(() => {
            window.onkeydown = (e) => {

                // 回车键登录
                if (!isLoginBtnDisabled.value && e.which === 13) {
                    login()
                }
            }
        })

        function login() {
            loginBtnValue.value = '登录中...'
            doLogin(user).then(rsp => {
            }).catch(err => {
                user.username = ''
            }).finally(() => {
                user.password = ''
                loginBtnValue.value = '登 录'
            })
        }

        return { ...toRefs(user), login, isLoginBtnDisabled, loginBtnValue };
    },
};
</script>
<style scoped>
#login-box {
    background-image: url(../../static/login-bg.jpg);
    background-attachment: fixed;
    background-repeat: no-repeat;
    background-size: cover;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    min-height: 100vh;
}

#login-box .login-form {
    min-width: 300px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    border: thin solid lightblue;
    border-radius: 5%;
    background: rgba(128, 128, 128, 0.6);
    padding: 20px;
    box-shadow: -1px 1px 1px blue, 1px 1px 1px orange;
}

#login-box .login-form .login-input {
    width: 100%;
    margin-top: 20px;
    padding: 40Px auto;
}

#login-box .login-form .login-btn {
    width: 50%;
    margin: 20px 0 10px 25%;
    padding: 40Px auto;
}

#login-box .login-form .login-btn .btn {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 10px auto 0 auto;
    font-size: 16px;
}
</style>